import { createSlice, PayloadAction } from '@reduxjs/toolkit';

export interface AddressState {
  community: string; // 小区名称
  building: string; // 楼栋号
  unit: string; // 单元号
  room: string; // 门牌号
  fullAddress?: string; // 完整地址字符串
}

const initialState: AddressState = {
  community: '',
  building: '',
  unit: '',
  room: '',
  fullAddress: '',
};

const addressSlice = createSlice({
  name: 'address',
  initialState,
  reducers: {
    setAddress: (state, action: PayloadAction<AddressState>) => {
      const { community, building, unit, room } = action.payload;
      state.community = community;
      state.building = building;
      state.unit = unit;
      state.room = room;

      // 生成完整地址字符串，当必要字段为空时进行处理
      if (!community && !building) {
        state.fullAddress = '';
      } else {
        const buildingText = building ? `${building}栋` : '';
        const unitText = unit ? `-${unit}单元` : '';
        const roomText = room ? `-${room}` : '';
        state.fullAddress = `${community || ''}${buildingText}${unitText}${roomText}`;
      }
    },
    clearAddress: (state) => {
      state.community = '';
      state.building = '';
      state.unit = '';
      state.room = '';
      state.fullAddress = '';
    },
  },
});

export const { setAddress, clearAddress } = addressSlice.actions;
export const addressReducer = addressSlice.reducer; 